package com.sprite.framework.entity;

import com.sprite.framework.entity.model.ModelEntityUtil;
import com.sprite.framework.entity.model.ModelField;
import com.sprite.framework.entity.util.EntityUtil;
import com.sprite.utils.UtilBeans;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

@SuppressWarnings("serial")
public class EntityObject extends LinkedHashMap<String, Object> {

	private String entityName;
	public String getEntityName() {
		return entityName;
	}
	public void setEntityName(String entityName) {
		this.entityName = entityName;
	}
	
	public void set(String prop, Object value) {
		super.put(prop, value);
	}
	
	public Integer getInteger(String prop) {
		return EntityUtil.convert(get(prop), Integer.class);
	}
	
	public int getInteger(String prop, int defaultValue) {
		Integer value = getInteger(prop); 
		if(value == null) {
			return defaultValue;
		}
		
		return value;
	}
	
	public Long getLong(String prop) {
		return EntityUtil.convert(get(prop), Long.class);
	}
	
	public Date getDate(String prop) {
		return EntityUtil.convert(get(prop), Date.class);
	}
	
	public BigDecimal getBigDecimal(String prop) {
		return EntityUtil.convert(get(prop), BigDecimal.class);
	}
	
	public String getString(String prop) {
		return EntityUtil.convert(get(prop), String.class);
	}
	
	public Boolean getBoolean(String prop) {
		return EntityUtil.convert(get(prop), Boolean.class);
	}
	
	public BigInteger getBigInteger(String prop) {
		return EntityUtil.convert(get(prop), BigInteger.class);
	}
	
	public Double getDouble(String prop) {
		return EntityUtil.convert(get(prop), Double.class);
	}

	/**
	 * 将对象转为 EntityObject
	 * @param entityName 实体全称
	 * @param object java bean
	 * @return EntityObject
	 */
	public static EntityObject map(String entityName, Object object) {
		EntityObject entityObject = new EntityObject();
		Map<String, Object> values = UtilBeans.toMap(object);
		for(ModelField field : ModelEntityUtil.getModelEntity(entityName).getFields()) {
			Object value = values.get(field.getFieldName());
			if(value != null) {
				entityObject.put(field.getFieldName(), value);
			}
		}
		
		return entityObject;
	}
}
